//
//  CommunityTableTableViewController.m
//  WeCommunity
//
//  Created by mac on 2017/8/9.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "CommunityTableTableViewController.h"
#import "PersonalHomePageViewController.h"

@interface CommunityTableTableViewController ()<DynamicClickContentDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, assign)BOOL isCanUseSideBack;  // 手势是否启动


@end

@implementation CommunityTableTableViewController

-(AdMobModel *)adMobModel
{
    for (id model in self.dataSource) {
        if ([model isKindOfClass:[AdMobModel class]]){
            _adMobModel = model;
            return _adMobModel;
        }
    }
    return nil;
}

-(NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        
    }
    return _dataSource;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addNotification];
    
    [self setupUserInterface];

}

-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    //导航控制器的第一个视图控制器关闭边缘返回手势
    if (self.navigationController.viewControllers.count == 1) {
        [self forbiddenSideBack];
    }else if (self.navigationController.viewControllers.count > 1){
        //恢复边缘返回手势
        [self resetSideBack];
    }
}

-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteDynamicContentNotification:) name:DELETE_CONTENT_NOTIKEY object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userInfoMangerUpdateUserData:) name:USERLOGIN_CHANGE_NOTIKEY object:nil];
}

-(void)beginLoadingData
{
    if (self.dataSource.count == 0) {
        [self.refreshHeader beginRefreshing];
    }
}



-(void)setupUserInterface
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    @weakify(self);
    self.refreshHeader = [CustomRefreshHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self headerRefreshData];
    }];
    self.tableView.mj_header = self.refreshHeader;
    
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshData)];
    [self.footer setTitle:@"" forState:MJRefreshStateIdle];
    [self.footer setTitle:@"" forState:MJRefreshStateRefreshing];
    self.tableView.mj_footer = self.footer;
}

#pragma mark -  取最后一条动态数据
-(DynamicModel *)getLastDynamicObject:(NSArray *)array;
{
    for (NSInteger i = array.count - 1; i >= 0; i --) {
        id model = array[i];
        if ([model isKindOfClass:[DynamicModel class]]) {
            return model;
        }
    }
    
    DynamicModel * model = [DynamicModel new];
    return model;
}

#pragma mark - 下拉刷新数据
-(void)headerRefreshData
{
    self.loadDataType = LoadDataType_ReLoadData;
    [self loadingData];
}
#pragma mark - 上拉加载数据
-(void)footerRefreshData
{
    self.loadDataType = LoadDataType_LoadData;
    [self loadingData];
}

#pragma mark - 加载数据
-(void)loadingData
{
    NSDate * loadDate = nil;
    if (self.loadDataType == LoadDataType_LoadData) {
        loadDate = [self getLastDynamicObject:self.dataSource].createDate;
    }
    
    [[DynamicServer shared] loadDynamicDataWithDataType:self.dataType
                                               loadDate:loadDate
                                              loadCount:20
                                               complete:^(BOOL success, NSString *error, NSArray *dataArray) {
                                                   if (success) {
                                                       if (self.loadDataType == LoadDataType_ReLoadData) {
                                                           [self.dataSource removeAllObjects];
                                                       }
                                                       [self.dataSource addObjectsFromArray:dataArray];
                                                       if (dataArray.count == 0) {
                                                           [self.footer setTitle:KHasLoadedAllTitle forState:MJRefreshStateIdle];
                                                           [self.footer setTitle:KHasLoadedAllTitle forState:MJRefreshStateRefreshing];
                                                       }else{
                                                           [self.footer setTitle:KDragOrClickToDragTitle forState:MJRefreshStateIdle];
                                                           [self.footer setTitle:KLoaddingMoreTitle forState:MJRefreshStateRefreshing];
                                                       }
                                                   }else{
                                                       [UITool showHudWithText:error withView:self.view];
                                                   }
                                                   [self endRefreshAnimation:success];
                                               }];
}

-(void)endRefreshAnimation:(BOOL)success
{
    if (success) {
        [(CustomRefreshHeader*)self.tableView.mj_header endRefreshingSuccess];
    }else{
        [(CustomRefreshHeader*)self.tableView.mj_header endRefreshingFail];
    }
    [self.tableView.mj_footer endRefreshing];
    [self.tableView reloadData];
}

#pragma mark - tableView delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id  model= self.dataSource[indexPath.row];
    if([model isKindOfClass:[DynamicModel class]]){
        return ((DynamicModel *)model).totalHeight;
    }else if ([model isKindOfClass:[AdMobModel class]]){
        if (IS_IPAD) {
            return  KScreen_Width * 0.8;
        }else{
            return  KScreen_Width;
        }
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id  model = self.dataSource[indexPath.row];
    if([model isKindOfClass:[DynamicModel class]]){
        static NSString * dynamicCellID = @"dynamicCell";
        DynamicCell * cell = [tableView dequeueReusableCellWithIdentifier:dynamicCellID];
        if (!cell) {
            cell =[[DynamicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:dynamicCellID];
            cell.delegate = self;
        }
        
        [cell creatCellWithModel:model showDelete:NO showReportCount:NO];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if ([model isKindOfClass:[AdMobModel class]]){
        static NSString * ADCellID = @"AdMobCell";
        DynamicAdMobTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ADCellID];
        if (!cell) {
            cell =[[DynamicAdMobTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ADCellID];
        }
        [cell creatCellWithModel:self.adMobModel root:self];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        return nil;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    id  model = self.dataSource[indexPath.row];
    if([model isKindOfClass:[DynamicModel class]]){
        
    }else if ([model isKindOfClass:[AdMobModel class]]){
        
    }
    NSLog(@"%@",model);
    
    [self canProcessNext];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    UIMenuController * menu = [UIMenuController sharedMenuController];
    [menu setMenuVisible:NO animated:YES];
}


#pragma mark - tableviewCell delegate
#pragma mark - 点赞.举报.more
-(void)likeDynamicWithSender:(UIView *)sender clickCell:(DynamicCell *)cell
{
    if (![self canProcessNext]) {
        return;
    }
    
    NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
    DynamicModel * model = self.dataSource[cellIndexPath.row];
    if (sender.tag == LikeBtn_tag) { //点赞
        
        [[DynamicServer shared] likeOrUnLikeDataWithDynamic:model complete:^(BOOL success, NSString *error, DynamicModel *model) {
            if (success) {
                [cell changeLikeNumWithDynamic:model];
            }else{
                [UITool showHudWithText:error withView:self.view];
            }
        }];
    }else if (sender.tag == ReportBtn_tag){ //举报
        
        [[DynamicServer shared] reportDynamicToAdmin:model complete:^(BOOL success, NSString *error, DynamicModel *model) {
            if (success) {
                [self sureAlertWithTitle:nil andMesg:KNSLocal(@"reportMessage")];
            }else{
                [UITool showHudWithText:error withView:self.view];
            }
        }];
    }else if (sender.tag == ContactBtn_tag){ // 点击用户头像
        
        PersonalHomePageViewController * homePageVC = [[PersonalHomePageViewController alloc] init];
        homePageVC.contact = model.contact;
        [self.navigationController pushViewController:homePageVC animated:YES];

    }
}
#pragma mark - 显示全部、隐藏
-(void)isShowMoreContent:(BOOL)showMore withCell:(DynamicCell *)cell sender:(UIButton *)sender
{
    NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadRowsAtIndexPaths:@[cellIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    });
    
}
#pragma mark - 点击文字中的链接
-(void)processCommunityUrlLink:(NSString *)link cell:(DynamicCell *)cell
{
    CWebViewController * webVC = [[CWebViewController alloc] init];
    webVC.linkUrl = link;
    [self.navigationController pushViewController:webVC animated:YES];
}

#pragma mark - 删除动态通知
-(void)deleteDynamicContentNotification:(NSNotification *)noti
{
    NSString * objectId = noti.object;
    for (id model in self.dataSource) {
        if ([model isKindOfClass:[DynamicModel class]]) {
            if ([((DynamicModel*)model).objectId isEqualToString:objectId]) {
                [self.dataSource removeObject:model];
                break;
            }
        }
    }
    [self.tableView reloadData];
}

#pragma mark - 登陆状态改变
-(void)userInfoMangerUpdateUserData:(NSNotification *)noti
{
    [self.tableView reloadData];
}
-(BOOL)canProcessNext
{
    if ([[GooGleAdMobMgr shared] showInterstitialWithVC:self]) {
        return NO;
    }
    
    if ([[UserInfoManger shared] needGotoLoginLogic]) {
        return NO;
    }
    return YES;
}

//一般不传title title有默认内容
-(void)sureAlertWithTitle:(NSString *)title andMesg:(NSString *)msg
{
    if (title.length == 0 || !title) {
        title = KNSLocal(@"alertTitle");
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController=[UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertAction=[UIAlertAction actionWithTitle:KNSLocal(@"alertOK") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:nil];
    });
}


#pragma mark - 关于自定义返回按钮后 解决滑动动画卡死的bug
/**
 * 禁用边缘返回
 */
-(void)forbiddenSideBack
{
    self.isCanUseSideBack = NO;
    //关闭ios右滑返回
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate=self;
    }
}

/*
 * 恢复边缘返回
 */
- (void)resetSideBack
{
    self.isCanUseSideBack = YES;
    //开启ios右滑返回
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer*)gestureRecognizer
{
    return self.isCanUseSideBack;
}


@end
